package huu.phong.sshchecker;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;

import com.maxmind.geoip.LookupService;

public class IPToLocation {
	
	//private static final Pattern ipPattern = Pattern.compile(">(\\d+{1,3}\\.\\d+{1,3}\\.\\d+{1,3}\\.\\d+{1,3})<.*?><a.*?>(.*?)</a>");
	
	private LookupService lookupService;
	
	public IPToLocation() {
		try {
			lookupService = new LookupService("GeoIP.dat", LookupService.GEOIP_MEMORY_CACHE);
		} catch (IOException e) {
		}
	}
	
	public String getRegion(String ip) throws IOException {
		return lookupService.getCountry(ip).getName();
	}
	
	public String getIPInformation(String ip) throws IOException {
		String ret = "";
		BufferedReader reader = getReader("http://geoiptool.com/en/?ip=" + ip);
		String line = null;
		while ((line = reader.readLine()) != null) {
			//System.out.println(line);
			if (line.contains("Country:")) {
				reader.readLine();
				reader.readLine();
				reader.readLine();
				reader.readLine();
				ret = reader.readLine().trim();
				break;
			}
		}
		reader.close();
		return ret.trim().equals("") ? "Unknow" : ret;
	}
	
	public InputStream getInputStream(String link) throws IOException{
		URL url = new URL(link);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		InputStream in = connection.getInputStream();
		if ("gzip".equalsIgnoreCase(connection.getContentEncoding())) in = new GZIPInputStream(in);
		return in;
	}
	
	public BufferedReader getReader(String link) throws IOException{
		return new BufferedReader(new InputStreamReader(getInputStream(link), "UTF-8"));
	}
	
	public static void main(String[] args) throws IOException {
		System.out.println(new IPToLocation().getIPInformation("199.195.177.9"));
	}
}
